package net.qqxh.shiro.config;


import net.qqxh.shiro.bootStrap.AbstractShiroService;
import net.qqxh.shiro.bootStrap.ShiroUser;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

public class RralmSimple extends AuthorizingRealm {

    private AbstractShiroService shiroService;
    /**
     * 授权
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        ShiroUser shiroUser = (ShiroUser) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(shiroUser.getRoles());

        return info;
    }

    /**
     * 认证
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        ShiroUser shiroUser = shiroService.getUserByLoginName(token.getUsername());
        if (shiroUser == null) {
            return null;
        }
        return new SimpleAuthenticationInfo(shiroUser, shiroUser.getPwd(), getName());
    }
    public void setShiroService(AbstractShiroService shiroService) {
        this.shiroService = shiroService;
    }
}
